package org.wx.herostory.services.handler;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.msg.GameMsgProtocol;
import org.wx.herostory.model.User;
import org.wx.herostory.services.encoder.CmdHandlerFactory;
import org.wx.herostory.services.encoder.ICmdHandler;
import org.wx.herostory.services.processor.MainMsgProcessor;
import org.wx.herostory.services.util.Broadcaster;
import org.wx.herostory.services.util.UserManager;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 消息处理Handler
 * @author: wangxun
 * @createDate: 2021/3/1
 * @version: 1.0
 */
@Slf4j
public class GameMsgHandler extends SimpleChannelInboundHandler {


    /**
     * 用户字典
     */
    static private final Map<Integer, User> _userMap = new HashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (null == ctx) {
            return;
        }

        try {
            super.channelActive(ctx);
            Broadcaster.addChannel(ctx.channel());
        } catch (Exception ex) {
            // 记录错误日志
            log.error(ex.getMessage(), ex);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (null == ctx ||
                null == msg) {
            return;
        }
        // 通过单线程的线程池串行执行任务
        MainMsgProcessor.getInstance().process(ctx,msg);
    }




    /**
     * 客户端掉线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        if(ctx == null){
            return;
        }
        super.handlerRemoved(ctx);

        // 获取ChannelContext中的userId , userId 在用户进场的时候进行的保存
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        log.info("用户掉线:{}",userId);
        // 信道管理删除信道
        Broadcaster.removeChannel(ctx.channel());
        if(userId == null){
            return;
        }
        // 用户管理删除用户
        UserManager.removeByUserId(userId);

        // 建立用户退出消息
        GameMsgProtocol.UserQuitResult.Builder builder = GameMsgProtocol.UserQuitResult.newBuilder();
        builder.setQuitUserId(userId);
        // 广播某个用户下线
        Broadcaster.broadcast(builder.build());
    }
}
